package com.big.es.service.impl;

import com.big.common.utils.StringReplace;
import com.big.es.service.ProductService;
import com.big.model.model.es.MerchandiseEsVo;
import com.big.model.model.merchandise.MerchandiseDetail;
import com.big.model.vo.merchandise.MerchanParams;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.DisMaxQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 搜索引擎
 */
@Service
@Slf4j
public class ProductServiceImpl implements ProductService {


    /**
     *    * 关键词高亮模糊搜索
     *      * 颜色: 橘黄 #ff6700
     * 思路：关键字字典用户搜索没有,可以转到商品的名称和关键语进行搜索
     */

    @Autowired
    RestHighLevelClient client;


    //商品数据
    @Value("${elasticsearch.indices1}")
    private String merchandise_es;

    //关键字字典
    @Value("${elasticsearch.indices2}")
    private String merchandise_keywords;




    /**
     * 关键字典
     * @param search
     * @return
     * @throws IOException
     */
    /**
     * 关键字与商品
     */
    @Override
    public List<MerchandiseEsVo> keyInfos(String search) throws IOException {
        //查询索引
        SearchRequest request = new SearchRequest();
        request.indices(merchandise_keywords);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        WildcardQueryBuilder name = QueryBuilders.wildcardQuery("name", "*"+search+"*");
        //构建高亮字段
        sourceBuilder.query(name);
        // 分页查询
        sourceBuilder.from(0);
        // 每页显示多少条 size
        sourceBuilder.size(50);
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 查询匹配
        SearchHits hits = response.getHits();
        List<MerchandiseEsVo> MerchandiseEss=new ArrayList<>();
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            MerchandiseEsVo merchandiseEsVo = new MerchandiseEsVo(
                    String.valueOf(hit.getSourceAsMap().get("value")),
                    String.valueOf(hit.getSourceAsMap().get("name")));
            log.info(String.valueOf(merchandiseEsVo));
            MerchandiseEss.add(merchandiseEsVo);
        }
        //商品名进行
        List<MerchandiseEsVo> merchandiseEsVos = this.ProInfos(search);
        merchandiseEsVos.forEach(item -> {
            MerchandiseEss.add(item);
        });
        return  MerchandiseEss;
    }

    /**
     * 处理同步显示数据 高亮
     * <font color='#ff6700'> </font>
     * @param page
     * @param size
     * @param merchanParams
     * @return
     */


    @Override
    public List<MerchandiseDetail> MerchandiseDetailESInfos(Long page, Long size, MerchanParams merchanParams) throws IOException {
        //查询索引
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
        SearchRequest request = new SearchRequest();
        request.indices(merchandise_es);
        WildcardQueryBuilder name = QueryBuilders.wildcardQuery("name", "*"+merchanParams.getSearch()+"*");
        WildcardQueryBuilder dintro = QueryBuilders.wildcardQuery("dintro", "*"+merchanParams.getSearch()+"*");
        //TODO 多条件模糊查询
        disMaxQueryBuilder.add(name);
        disMaxQueryBuilder.add(dintro);
        // 分页查询
        sourceBuilder.from(Math.toIntExact(page));
        // 每页显示多少条 size
        sourceBuilder.size(Math.toIntExact(size));
        sourceBuilder.query(disMaxQueryBuilder);
        request.source(sourceBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 查询匹配
        SearchHits hits = response.getHits();
        System.out.println("took:" + response.getTook());
        System.out.println("total:" + hits.getTotalHits());
        List<MerchandiseDetail> MerchandiseEss=new ArrayList<>();
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            MerchandiseDetail merchandiseDetail = new MerchandiseDetail();
            //进行高亮名称和简介

            String highlightDintro = String.valueOf(hit.getSourceAsMap().get("dintro"));
            String introduction = StringReplace.Introduction(highlightDintro, merchanParams.getSearch());

            //写入实体类
            merchandiseDetail.setDIntro(introduction);
            merchandiseDetail.setDId(String.valueOf(hit.getSourceAsMap().get("id")));
            merchandiseDetail.setDImage(String.valueOf(hit.getSourceAsMap().get("dimage")));
            merchandiseDetail.setCateId(Integer.valueOf(String.valueOf(hit.getSourceAsMap().get("cate_id"))));
            if(hit.getSourceAsMap().get("tag")!=null){
                merchandiseDetail.setTag(Integer.valueOf(String.valueOf(hit.getSourceAsMap().get("tag"))));
            }
            merchandiseDetail.setId((Long) hit.getSourceAsMap().get("id"));
//             original_price
            Map<String,Object> params=new HashMap<>();
            params.put("selling_price", hit.getSourceAsMap().get("sellingprice"));
            params.put("original_price", hit.getSourceAsMap().get("originalprice"));
            //名字高亮
            String nameHighlight = StringReplace.Nametion(String.valueOf(hit.getSourceAsMap().get("name")), merchanParams.getSearch());
            params.put("name",nameHighlight);
            merchandiseDetail.setParam(params);
            log.info(String.valueOf(merchandiseDetail));
            MerchandiseEss.add(merchandiseDetail);
        }
        return  MerchandiseEss;
    }


    public List<MerchandiseEsVo> ProInfos(String search) throws IOException {
        //查询索引
        SearchRequest request = new SearchRequest();
        request.indices(merchandise_es);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        WildcardQueryBuilder name = QueryBuilders.wildcardQuery("name", "*"+search+"*");
        //构建高亮字段
        sourceBuilder.query(name);
        // 分页查询
        sourceBuilder.from(0);
        // 每页显示多少条 size
        sourceBuilder.size(50);
        request.source(sourceBuilder);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 查询匹配
        SearchHits hits = response.getHits();
        List<MerchandiseEsVo> MerchandiseEss=new ArrayList<>();
        for (SearchHit hit : hits) {
            //输出每条查询的结果信息
            MerchandiseEsVo merchandiseEsVo = new MerchandiseEsVo(
                    String.valueOf(hit.getSourceAsMap().get("id")),
                    String.valueOf(hit.getSourceAsMap().get("name")));
            log.info(String.valueOf(merchandiseEsVo));
            MerchandiseEss.add(merchandiseEsVo);
        }
        return  MerchandiseEss;
    }


    /**
     * 分词
     */




}
